package com.czn.shopdemo.aop;

import com.czn.shopdemo.model.Logs;
import com.czn.shopdemo.service.LogsService;
import com.czn.shopdemo.utils.TokenInfoUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

@Aspect
@Component
@Order(1)
public class LogAspect {

    @Autowired
    private LogsService logsService;

    @Pointcut("execution(public * com.czn.shopdemo.controller.*.*(..))")
    public void webLog() {
    }


    @Before("webLog()")
    public void deBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        Logs logs = new Logs();
        logs.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
        logs.setUserId(String.valueOf(TokenInfoUtil.getUserId(request)));
        logs.setUserName(TokenInfoUtil.getUserName(request));
        logs.setUpdateTime(new Date());
        logs.setCreateTime(new Date());
        // 接收到请求，记录请求内容
        logs.setUri(request.getRequestURI());
        logs.setMethods(request.getMethod());
        logs.setClassName(joinPoint.getSignature().getDeclaringTypeName());
        logs.setMethodName(joinPoint.getSignature().getName());
        logs.setIp(request.getRemoteAddr());
        logs.setArgs(Arrays.toString(joinPoint.getArgs()));
        logsService.save(logs);
    }
}